import { USD } from '@/constants/global'
import { filterNumber } from '@/utils/number'

// type: open, high, last, low, deal
export function usdPrice (symbol, type, marketState) {
  const { realTimeQuotes, coinPairInfo } = marketState
  if (realTimeQuotes[symbol] && coinPairInfo[symbol]) {
    const coinPair = realTimeQuotes[symbol]
    if (coinPairInfo[symbol].money.includes('USD')) {
      return filterNumber(coinPair[type])
    }
    const baseSymbol = coinPairInfo[symbol].money + 'USDT'
    if (realTimeQuotes[baseSymbol]) {
      const usdtPair = realTimeQuotes[baseSymbol]
      const num1 = filterNumber(coinPair[type])
      const num2 = filterNumber(usdtPair[type])
      return num1 * num2
    }
  }
  return 0
}

export function applyCurrencyPriceWithState (state) {
  return (symbol, type) => {
    const { currency, market } = state
    if (currency.name === USD) {
      return usdPrice(symbol, type, market)
    }
    const { usd2cny } = market
    const dollar = usdPrice(symbol, type, market)
    return dollar * usd2cny
  }
}

// 排行榜（插排）
function insertionSort (arr, extraData, current, sortBy) {
  const [name, item] = current
  arr.includes(name) && arr.splice(arr.indexOf(name), 1)

  // 过滤掉涨跌幅太小的交易对
  // const rate = ((item.last - item.open) / item.open) * 100
  // if ((rate > -0.01 && rate < 0) || (rate < 0.01 && rate > 0)) { return }

  const len = arr.length
  let preIndex = len - 1
  if (sortBy === 'desc') {
    while (
      preIndex >= 0 &&
      ((extraData[arr[preIndex]].last - extraData[arr[preIndex]].open) / extraData[arr[preIndex]].open) < ((item.last - item.open) / item.open)
    ) {
      // arr.splice(preIndex + 1, 1, arr[preIndex])
      arr[preIndex + 1] = arr[preIndex]
      preIndex--
    }
  } else {
    while (
      preIndex >= 0 &&
      ((extraData[arr[preIndex]].last - extraData[arr[preIndex]].open) / extraData[arr[preIndex]].open) > ((item.last - item.open) / item.open)
    ) {
      // arr.splice(preIndex + 1, 1, arr[preIndex])
      arr[preIndex + 1] = arr[preIndex]
      preIndex--
    }
  }
  arr.splice(preIndex + 1, 1, name)
}

export function updateUpAndDownRank (state, data) {
  const { realTimeQuotes, upRank, downRank } = state
  const [name, item] = data
  const isUp = item.last >= item.open
  if (isUp) {
    downRank.includes(name) && downRank.splice(downRank.indexOf(name), 1)
    insertionSort(upRank, realTimeQuotes, data, 'desc')
  } else {
    upRank.includes(name) && upRank.splice(upRank.indexOf(name), 1)
    insertionSort(downRank, realTimeQuotes, data)
  }
}
